package com.example.tourpal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tourpal.model.Consume;
import com.example.tourpal.model.Journey;
import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.PublishJourneyLishenter;
import com.example.tourpal.model.LocalDataLoader.SquareLishenter;
import com.example.tourpal.model.LocalDataLoaderHelp;
import com.example.tourpal.model.Page;
import com.example.tourpal.model.Person;
import com.example.tourpal.model.Plan;
import com.example.tourpal.model.User;
import com.example.tourpal.model.UserDataManager;
import com.example.tourpal.model.UserDataManager.UserDataLishenter;
import com.example.tourpal.user.LoginActivity;
import com.example.tourpal.user.RegisterActivity;
import com.example.tourpal.user.RoundImageView;
import com.example.tourpal.user.UserHeadActivity;
import com.example.tourpal.util.SharePreferencesManager;
import com.example.tourpal.util.SharePreferencesManager.LoginInfo;
import com.example.tourpal.volley.WeatherVolleyTest;
import com.example.tourpal.widget.CustomPagerAdapter;
import com.example.tourpal.widget.CustomViewPager;
import com.example.tourpal.widget.DynamicListView;
import com.example.tourpal.widget.DynamicListView.DynamicListViewListener;
import com.example.tourpal.widget.HomePlanAdapter;
import com.example.tourpal.widget.SpotItem;

public class MainActivity extends Activity implements OnClickListener,
		DynamicListViewListener {

	private static final String UNDER_LINE = "-";

	private Context context;

	private ViewGroup rootGroup;
	private CustomViewPager viewPaper;
	private ViewPager guidePager;

	private TextView homeTextView;
	private TextView planTextView;
	private TextView packageTextView;
	private List<View> pageViews;

	private LinearLayout viewTab;
	// private int currentTab = 0;

	// home
	private DynamicListView overViewPlanListView;
	private HomePlanAdapter overViewPlanAdapter;
	private ImageView planSearch;

	// home data
	public int[] guides = new int[] { R.drawable.guide_1, R.drawable.guide_2 };

	private List<HashMap<String, Object>> overplanList;
	private int currentPage = 1;
	// private int currentItem = 0;
	// private int allPage = 0;
	// private int allItem = 0;

	// creatPlan
	private int AddSpotId;
	private int planId = 0;
	private EditText planName;
	private EditText planDescription;
	private Button releaseBt;
	private LinearLayout spotListView;
	private LinearLayout compareBar;
	private View inputTarget;
	// private ScrollView spotScroll;
	// private List<List<String>> spotConsumList;

	private ImageView foodIndicate;
	private ImageView liveIndicate;
	private ImageView goIndicate;
	private ImageView swimIndicate;
	private ImageView amuseIndicate;
	private ImageView buyIndicate;
	private ImageView otherIndicate;

	private int currentConsumResID;
	private List<Plan> sourcePlans;

	// myPackage
	private User mUser;// = User.getDefaultUser();
	private RelativeLayout userTitleLayout;
	private ImageView messageSign;
	private TextView phoneNumber;
	private Button editNumberBt;
	private RoundImageView head;
	private TextView myPlan;
	private TextView mySetting;
	private TextView myFeedback;
	private Button logoutBt;
	private TextView register;

	private InputMethodManager imm;
	private SharePreferencesManager mSharePreferencesManager;
	private SimpleDateFormat sFormat;
	private SimpleDateFormat tFormat;

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				if (overViewPlanAdapter != null) {
					overViewPlanAdapter = null;
				}
				overViewPlanAdapter = new HomePlanAdapter(context,
						overplanList, true);
				overViewPlanListView.setAdapter(overViewPlanAdapter);
				overViewPlanListView.doneRefresh();
				Toast.makeText(MainActivity.this,
						"Loading " + msg.arg1 + " Dates.", Toast.LENGTH_LONG)
						.show();

				overViewPlanListView.setSelection(0);
			} else if (msg.what == 1) {
				overViewPlanAdapter.notifyDataSetChanged();
				overViewPlanListView.doneMore();
				Toast.makeText(MainActivity.this,
						"More " + msg.arg1 + " Dates.", Toast.LENGTH_LONG)
						.show();

				overViewPlanListView.setSelection((currentPage - 1) * 20);
			} else if (msg.what == 2) {
				showUserInfo();
				// super.handleMessage(msg);
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_viewpage);
		mSharePreferencesManager = new SharePreferencesManager(this);
		sFormat = new SimpleDateFormat(getText(R.string.date_format_1)
				.toString(), Locale.getDefault());
		tFormat = new SimpleDateFormat(getText(R.string.date_format_2)
				.toString(), Locale.getDefault());

		context = this;

		rootGroup = null;

		viewPaper = (CustomViewPager) findViewById(R.id.mainPager);
		guidePager = (ViewPager) findViewById(R.id.viewGuide);

		viewTab = (LinearLayout) findViewById(R.id.mainTab);
		homeTextView = (TextView) findViewById(R.id.lvHome);
		planTextView = (TextView) findViewById(R.id.lvPlan);
		packageTextView = (TextView) findViewById(R.id.lvPackage);

		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		init();
//		new WeatherVolleyTest().getWeatherDataTest(this);
	}

	@SuppressLint("ClickableViewAccessibility")
	private void init() {

		LayoutInflater mInflater = getLayoutInflater();

		pageViews = new ArrayList<View>();
		pageViews.add(mInflater.inflate(R.layout.travel_home_page, rootGroup));
		pageViews.add(mInflater.inflate(R.layout.travel_editplan_page,
				rootGroup));
		pageViews.add(mInflater
				.inflate(R.layout.travel_package_page, rootGroup));

		viewPaper.setAdapter(new CustomPagerAdapter(pageViews));
		viewPaper.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent me) {
				return false;
			}
		});
		viewPaper.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				updateTagUI(index);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
		viewPaper.setScrollEnabled(false);

		SharedPreferences sp = getSharedPreferences("guide",
				Activity.MODE_PRIVATE);
		if (!sp.getBoolean("good", false)) {
			setupGuidePage();
		}
		setupHomePage();
		setupCreatPlanPage();
		setupMyPage();
		registerUserHeadReceiver();
		autoLogin();
		updateTagUI(0);
	}

	private void setupGuidePage() {
		List<View> mList = new ArrayList<View>();
		LayoutInflater inflat = LayoutInflater.from(this);
		View item = null;

		for (int index : guides) {
			item = inflat.inflate(R.layout.page_guide, rootGroup);
			item.setBackgroundResource(index);
			mList.add(item);
		}

		item = inflat.inflate(R.layout.page_guide, rootGroup);
		item.setBackgroundResource(R.drawable.guide_3);
		TextView start = (TextView) item.findViewById(R.id.start);
		start.setVisibility(View.VISIBLE);
		start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				guidePager.setVisibility(View.GONE);
				SharedPreferences sp = getSharedPreferences("guide",
						Activity.MODE_PRIVATE);
				sp.edit().putBoolean("good", true).commit();
			}
		});
		mList.add(item);

		guidePager.setAdapter(new CustomPagerAdapter(mList));
	}

	private void setupHomePage() {
		homeTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateTagUI(0);
			}
		});

		final View view = pageViews.get(0);

		planSearch = (ImageView) view.findViewById(R.id.planSearch);
		planSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(context, PlanSearchActivity.class);
				startActivity(intent);

				overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
			}
		});

		overViewPlanListView = (DynamicListView) view
				.findViewById(R.id.overViewPlan);

		requestPlanData(1, 0);

		if (overViewPlanAdapter != null) {
			overViewPlanAdapter = null;
		}

		overViewPlanAdapter = new HomePlanAdapter(this, overplanList, true);
		overViewPlanListView.setAdapter(overViewPlanAdapter);
		overViewPlanListView.setSelector(R.drawable.home_item_bg);
		overViewPlanListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int index, long l) {

				if (index == 1) {
					return;
				}
				if (index > 1) {
					Intent intent = new Intent();
					intent.setClass(context, PlanOverViewActivity.class);
					intent.putExtra("planID", v.getId());
					intent.putExtra("user", mUser);
					intent.putExtra("planName", overplanList.get(index - 1)
							.get("planName").toString());
					intent.putExtra("planDate", overplanList.get(index - 1)
							.get("planDate").toString());
					intent.putExtra(
							"planUserId",
							Integer.valueOf(overplanList.get(index - 1)
									.get("planUserId").toString()));
					startActivity(intent);
					overridePendingTransition(R.anim.sub_enter,
							R.anim.main_exit);
				}
			}
		});

		overViewPlanListView.setDoMoreWhenBottom(false);
		overViewPlanListView.setOnRefreshListener(this);
		overViewPlanListView.setOnMoreListener(this);
	}

	private void requestPlanData(int index, final int doType) {
		if (doType == 0) {
			overplanList = null;
			overplanList = new ArrayList<HashMap<String, Object>>();
			overplanList.add(new HashMap<String, Object>());
		}

		LocalDataLoader loader = new LocalDataLoader(context);
		loader.startLoadSquareData(index, new SquareLishenter() {

			@Override
			public void requestSquareList(List<Person> persons, Page page) {

				List<HashMap<String, Object>> tempList = new ArrayList<HashMap<String, Object>>();
				List<Integer> allHeadRes = getRandomPersonHeadRes(persons
						.size());
				for (int i = 0; i < persons.size(); i++) {
					Person person = persons.get(i);
					HashMap<String, Object> itemHashMap = new HashMap<String, Object>();

					itemHashMap.put("planId", person.getJourneyId());
					itemHashMap.put("headPic", allHeadRes.get(i));
					itemHashMap.put("followSign", person.isIspublic());
					itemHashMap.put("planName", person.getName());
					itemHashMap.put("planDestination", person.getDestination());
					try {
						String start = tFormat.format(sFormat.parse(person
								.getStartTime()));
						String end = tFormat.format(sFormat.parse(person
								.getEndTime()));
						itemHashMap.put("planDate", start + UNDER_LINE + end);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					itemHashMap.put("planHint", person.getDestination());
					itemHashMap.put("goodCnt", person.getPraiseNum());
					itemHashMap.put("commentCnt", person.getCommentNum());
					itemHashMap.put("planUserId", person.getUserId());

					tempList.add(itemHashMap);
				}

				synchronized (overplanList) {
					overplanList.addAll(tempList);
				}

				handler.sendMessage(handler.obtainMessage(doType,
						tempList.size(), 0));
				// handler.sendEmptyMessage(doType);

				if (page != null) {
					// allPage = page.getPageCount();
					Log.e("YLQ", "PageNo:" + page.getPageNo());
					// currentItem = page.getPageSize();
					// allItem = page.getRowCount();
				}

			}

		});
	}

	private void setupCreatPlanPage() {
		planTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mUser == null) {
					loginAlert();
				} else {
					updateTagUI(1);
				}
			}
		});

		final View view = pageViews.get(1);
		planName = (EditText) view.findViewById(R.id.planName);

		planDescription = (EditText) view.findViewById(R.id.planDescription);

		releaseBt = (Button) view.findViewById(R.id.release);
		releaseBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (check()) {
					postPlan();
				}

			}

		});

		spotListView = (LinearLayout) view.findViewById(R.id.spotListView);

		// spotScroll = (ScrollView) view.findViewById(R.id.spotScroll);

		setupInputView(view);
		setupSpotListView();

	}

	private void setupInputView(final View view) {
		compareBar = (LinearLayout) view.findViewById(R.id.compareBar);
		foodIndicate = (ImageView) view.findViewById(R.id.foodIndicate);
		foodIndicate.setOnClickListener(this);
		liveIndicate = (ImageView) view.findViewById(R.id.liveIndicate);
		liveIndicate.setOnClickListener(this);
		goIndicate = (ImageView) view.findViewById(R.id.goIndicate);
		goIndicate.setOnClickListener(this);
		swimIndicate = (ImageView) view.findViewById(R.id.swimIndicate);
		swimIndicate.setOnClickListener(this);
		amuseIndicate = (ImageView) view.findViewById(R.id.amuseIndicate);
		amuseIndicate.setOnClickListener(this);
		buyIndicate = (ImageView) view.findViewById(R.id.buyIndicate);
		buyIndicate.setOnClickListener(this);
		otherIndicate = (ImageView) view.findViewById(R.id.otherIndicate);
		otherIndicate.setOnClickListener(this);
	}

	public void showInputView(View v) {

		if (compareBar.getVisibility() == View.GONE) {
			compareBar.setVisibility(View.VISIBLE);

			viewTab.setVisibility(View.GONE);
			viewPaper.setScrollEnabled(false);

			imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

		}
	}

	@Override
	public void onClick(View v) {
		updateIndicateUI(v.getId());
	}

	public void updateIndicateUI(int index) {
		foodIndicate.setBackgroundResource(R.drawable.food_middle_idle);
		liveIndicate.setBackgroundResource(R.drawable.live_middle_idle);
		goIndicate.setBackgroundResource(R.drawable.go_middle_idle);
		swimIndicate.setBackgroundResource(R.drawable.swim_middle_idle);
		amuseIndicate.setBackgroundResource(R.drawable.amuse_middle_idle);
		buyIndicate.setBackgroundResource(R.drawable.buy_middle_idle);
		otherIndicate.setBackgroundResource(R.drawable.other_middle_idle);

		int indicate = 7;

		switch (index) {
		case R.id.foodIndicate:
			foodIndicate.setBackgroundResource(R.drawable.food_middle_passed);
			currentConsumResID = R.drawable.food;
			indicate = R.string.default_consum_for_food;
			break;
		case R.id.liveIndicate:
			liveIndicate.setBackgroundResource(R.drawable.live_middle_passed);
			currentConsumResID = R.drawable.live;
			indicate = R.string.default_consum_for_live;
			break;
		case R.id.goIndicate:
			goIndicate.setBackgroundResource(R.drawable.go_middle_passed);
			currentConsumResID = R.drawable.go;
			indicate = R.string.default_consum_for_go;
			break;
		case R.id.swimIndicate:
			swimIndicate.setBackgroundResource(R.drawable.swim_middle_passed);
			currentConsumResID = R.drawable.swim;
			indicate = R.string.default_consum_for_swim;
			break;
		case R.id.amuseIndicate:
			amuseIndicate.setBackgroundResource(R.drawable.amuse_middle_passed);
			currentConsumResID = R.drawable.amuse;
			indicate = R.string.default_consum_for_amuse;
			break;
		case R.id.buyIndicate:
			buyIndicate.setBackgroundResource(R.drawable.buy_middle_passed);
			currentConsumResID = R.drawable.buy;
			indicate = R.string.default_consum_for_buy;
			break;
		case R.id.otherIndicate:
			otherIndicate.setBackgroundResource(R.drawable.other_middle_passed);
			currentConsumResID = R.drawable.other;
			indicate = R.string.default_consum_for_other;
			break;
		default:
			break;
		}

		EditText toView = (EditText) inputTarget;
		toView.setHint(indicate);
		Drawable cid = getResources().getDrawable(currentConsumResID);
		cid.setBounds(0, 0, cid.getMinimumWidth(), cid.getMinimumHeight());
		toView.setCompoundDrawables(cid, null, null, null);

	}

	private void setupSpotListView() {

		final LinearLayout.LayoutParams spotItemParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		spotItemParams.setMargins(0, 16, 0, 0);
		spotListView.addView(newSpotItem(0), 0, spotItemParams);

		Button spotAddBt = (Button) spotListView.findViewById(R.id.spotAdd);
		spotAddBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int index = spotListView.getChildCount() - 1;
				spotListView.addView(newSpotItem(index), index, spotItemParams);
			}
		});

	}

	private SpotItem newSpotItem(int index) {
		setAddSpotId(index);
		SpotItem spotItem = new SpotItem(context);
		spotItem.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				if (spotListView.getChildCount() == 2) {
					Toast.makeText(context, "default not delete",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(context, "delete", Toast.LENGTH_SHORT)
							.show();
					spotListView.removeView(v);
				}
				return true;
			}
		});

		return spotItem;
	}

	private void setupMyPage() {

		packageTextView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				updateTagUI(2);
			}
		});

		final View view = pageViews.get(2);

		userTitleLayout = (RelativeLayout) view.findViewById(R.id.userTitle);

		messageSign = (ImageView) view.findViewById(R.id.messageSign);
		messageSign.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				intent.setClass(context, MyMessageActivity.class);
				startActivity(intent);

				overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
			}
		});

		phoneNumber = (TextView) view.findViewById(R.id.phoneNumber);
		editNumberBt = (Button) view.findViewById(R.id.editPhoneNumber);
		editNumberBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Toast.makeText(context, "go to phoneNumberEditActivity",
						Toast.LENGTH_SHORT).show();
			}
		});

		head = (RoundImageView) view.findViewById(R.id.headPic);
		head.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				goUserHeadActivity();
			}
		});

		myPlan = (TextView) view.findViewById(R.id.myPlan);
		myPlan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mUser == null) {
					loginAlert();
				} else {
					Intent intent = new Intent();
					intent.setClass(context, MyPlanActivity.class);
					intent.putExtra("user", mUser);
					startActivityForResult(intent, MyPlanActivity.RESULT_BACK);
					overridePendingTransition(R.anim.sub_enter,
							R.anim.main_exit);
				}
			}
		});

		mySetting = (TextView) view.findViewById(R.id.mySetting);
		mySetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (mUser == null) {
					loginAlert();
				} else {
					// start mySetting activity
				}
			}
		});

		myFeedback = (TextView) view.findViewById(R.id.myFeedback);
		myFeedback.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// start myFeedback activity
			}
		});

		logoutBt = (Button) view.findViewById(R.id.logout);
		logoutBt.setVisibility(View.GONE);
		logoutBt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				logout(v);
			}

		});

		register = (TextView) view.findViewById(R.id.register);
		register.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				login();
			}
		});
	}

	protected void updateTagUI(int current) {
		viewPaper.setCurrentItem(current);

		Drawable drawable = null;
		// currentTab = current;

		if (current == 0) {
			drawable = getResources().getDrawable(R.drawable.home_tab_on);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			homeTextView.setCompoundDrawables(null, drawable, null, null);
			homeTextView.setTextColor(0xff2ba47b);
			drawable = getResources().getDrawable(R.drawable.me_tab_off);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			packageTextView.setCompoundDrawables(null, drawable, null, null);
			packageTextView.setTextColor(0xff929292);
			planTextView.setBackgroundResource(R.drawable.plan_tab_off);
		} else if (current == 2) {
			drawable = getResources().getDrawable(R.drawable.home_tab_off);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			homeTextView.setCompoundDrawables(null, drawable, null, null);
			homeTextView.setTextColor(0xff999999);
			drawable = getResources().getDrawable(R.drawable.me_tab_on);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			packageTextView.setCompoundDrawables(null, drawable, null, null);
			packageTextView.setTextColor(0xff2ba47b);
			planTextView.setBackgroundResource(R.drawable.plan_tab_off);
		} else {
			planTextView.setBackgroundResource(R.drawable.plan_tab_on);
			drawable = getResources().getDrawable(R.drawable.home_tab_off);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			homeTextView.setCompoundDrawables(null, drawable, null, null);
			homeTextView.setTextColor(0xff999999);
			drawable = getResources().getDrawable(R.drawable.me_tab_off);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(),
					drawable.getMinimumHeight());
			packageTextView.setCompoundDrawables(null, drawable, null, null);
			packageTextView.setTextColor(0xff929292);
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null) {
			int spotId = data.getIntExtra("spotId", 0);
			String spotSet = data.getStringExtra("spotSet");
			SpotItem spotItem = (SpotItem) spotListView.getChildAt(spotId);

			if (resultCode == PlanOverViewActivity.RESULT_BACK) {
				// get plan
			} else if (resultCode == SpotOverViewActivity.RESULT_BACK) {
				Log.e("YLQ", spotId + ":" + spotSet);

				spotItem.spotName.setText(spotSet);
			} else if (resultCode == SpotDateSetActivity.RESULT_BACK) {
				Log.e("YLQ", spotId + ":" + spotSet);

				spotItem.spotDate.setText(spotSet);
			} else if (resultCode == PartnerSettingActivity.RESULT_BACK) {
				Log.e("YLQ", spotId + ":" + spotSet);

				if (spotSet.equals("")) {
					spotItem.setFollow(false);
				} else {
					spotItem.setFollow(true);
				}
				spotItem.setFollowSetContent(spotSet);

			} else if (resultCode == MyPlanActivity.RESULT_BACK) {
				cleanReleasedPlan(true);
				Journey editJourney = (Journey) data
						.getSerializableExtra("editJourney");
				sourcePlans = editJourney.getPlans();
				fillCreatPlan(editJourney);
				updateTagUI(1);

			} else if (resultCode == RegisterActivity.RESULT_REGISTER
					|| resultCode == LoginActivity.RESULT_LOGIN) {
				Bundle bundle = data.getExtras();
				mUser = (User) bundle.get("user");
				Log.i("chengongguo", "register " + mUser.toString());
				// showUserInfo();
				handler.sendEmptyMessage(2);
			} else {

			}
		}
	}

	private void fillCreatPlan(Journey editJourney) {
		planId = editJourney.getId();
		planName.setText(editJourney.getName());
		String[] destElem = editJourney.getDestination().split(UNDER_LINE);
		planDescription.setText(destElem[destElem.length - 1]);

		LinearLayout.LayoutParams spotItemParams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		spotItemParams.setMargins(0, 16, 0, 0);

		int spotCnt = editJourney.getPlans().size();
		for (int i = 0; i < spotCnt; i++) {
			Plan plan = editJourney.getPlans().get(i);
			spotListView.addView(fillSpotItem(i, plan), i, spotItemParams);
		}
	}

	private View fillSpotItem(int index, Plan plan) {
		setAddSpotId(index);
		SpotItem spotItem = new SpotItem(context);
		spotItem.setSpotId(plan.getId());
		spotItem.spotName.setText(plan.getName());
		spotItem.spotDate.setText(plan.getStartTime() + UNDER_LINE
				+ plan.getEndTime());
		if (plan.getIspublic() == 1) {
			spotItem.setFollow(true);
			spotItem.setFollowSetContent(plan.getDescription());
		} else {
			spotItem.setFollow(false);
		}
		spotItem.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				if (spotListView.getChildCount() == 2) {
					Toast.makeText(context, "default not delete",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(context, "delete", Toast.LENGTH_SHORT)
							.show();
					spotListView.removeView(v);
				}
				return true;
			}
		});

		for (int i = 0; i < plan.getConsumes().size(); i++) {
			spotItem.addConsunItem(plan.getConsumes().get(i));
		}

		return spotItem;
	}

	public int getAddSpotId() {
		return AddSpotId;
	}

	public void setAddSpotId(int addSpotId) {
		AddSpotId = addSpotId;
	}

	// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>wait test
	@Override
	public boolean onRefreshOrMore(DynamicListView dynamicListView,
			boolean isRefresh) {
		if (!isNetworkAvailable()) {
			overViewPlanListView.doneRefresh();
			overViewPlanListView.doneMore();
		}

		if (isRefresh) {
			requestPlanData(1, 0);

		} else {
			Log.e("YLQ", "currentPage=" + currentPage);
			currentPage++;
			requestPlanData(currentPage, 1);

		}
		return false;
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {// cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	private void postPlan() {
		Journey journey = new Journey();
		journey.setId(planId);
		journey.setName(planName.getText().toString());

		List<Plan> spotList = new ArrayList<Plan>();

		int isPublic = 0;
		String destination = "";
		for (int i = 0; i < spotListView.getChildCount() - 1; i++) {
			SpotItem spItem = (SpotItem) spotListView.getChildAt(i);

			Plan spotItem = new Plan();
			List<Consume> consumes = new ArrayList<Consume>();
			spotItem.setId(spItem.getSpotId());
			spotItem.setDescription(spItem.getFollowSetContent());
			spotItem.setIspublic(spItem.getFollow());
			if (spItem.getFollow() == 1) {
				isPublic = 1;
			}
			for (int j = 0; j < spItem.getChildCount() - 1; j++) {
				if (j == 0) {
					RelativeLayout rLayout = (RelativeLayout) spItem
							.getChildAt(0);

					TextView sn = (TextView) rLayout.getChildAt(0);
					// TextView fs = (TextView) rLayout.getChildAt(1);
					String spotnm = sn.getText().toString();
					spotItem.setName(spotnm);
					destination += spotnm + UNDER_LINE;

				} else if (j == 1) {
					TextView sd = (TextView) spItem.getChildAt(j);
					String[] date = sd.getText().toString().split(UNDER_LINE);
					spotItem.setStartTime(date[0]);
					spotItem.setEndTime(date[1]);
				} else if (j == 2) {

				} else {
					Consume consume = new Consume();
					EditText ci = (EditText) spItem.getChildAt(j);
					String text = ci.getText().toString();
					consume.setClassOrder(j - 2);// classOrder
					if (text.trim().equals("")) {
						consume.setDescription(getResources().getString(
								R.string.default_consum_text));// description
					} else {
						consume.setDescription(text);// description
					}
					consume.setType(getConsumeHint(ci.getHint().toString()));// type
					Date curDate = new Date(System.currentTimeMillis());
					consume.setCreateTime(new SimpleDateFormat(getText(
							R.string.date_format_3).toString(), Locale
							.getDefault()).format(curDate));
					consumes.add(consume);
				}
			}

			spotItem.setConsumes(consumes);
			spotList.add(spotItem);
			Log.e("YLQ", "add consumList<<<<<");
		}

		spotList = diffPlans(spotList, sourcePlans);
		sourcePlans = null;

		journey.setPlans(spotList);
		journey.setDestination(destination
				+ planDescription.getText().toString());
		journey.setStartTime(spotList.get(0).getStartTime());
		journey.setEndTime(spotList.get(spotList.size() - 1).getEndTime());
		journey.setIspublic(isPublic);
		journey.setPraiseNum(0);
		journey.setUser(mUser);

		Toast.makeText(context, "Post Service!!! ", Toast.LENGTH_SHORT).show();
		Log.e("YLQ", journey.toString());
		LocalDataLoader loader = new LocalDataLoader(context);
		loader.publishJourney(journey, new PublishJourneyLishenter() {

			@Override
			public void requestPublishResult(int code) {
				switch (code) {
				case LocalDataLoaderHelp.PUBLISH_JOURNEY_DONE_ACTION:// publish
					cleanReleasedPlan(false);// success
					break;
				case LocalDataLoaderHelp.PUBLISH_ERROR_ACTION:// publish error

					break;
				case LocalDataLoaderHelp.NETWORK_ERROR_ACTION:// network error

					break;
				default:
					break;
				}
			}
		});

	}

	private int getConsumeHint(String hint) {
		if (hint.equals(getResources().getString(
				R.string.default_consum_for_food))) {
			return 1;
		}
		if (hint.equals(getResources().getString(
				R.string.default_consum_for_live))) {
			return 2;
		}
		if (hint.equals(getResources()
				.getString(R.string.default_consum_for_go))) {
			return 3;
		}
		if (hint.equals(getResources().getString(
				R.string.default_consum_for_swim))) {
			return 4;
		}
		if (hint.equals(getResources().getString(
				R.string.default_consum_for_amuse))) {
			return 5;
		}
		if (hint.equals(getResources().getString(
				R.string.default_consum_for_buy))) {
			return 6;
		} else {
			return 7;
		}

	}

	protected boolean check() {
		if (planName.getText().toString().isEmpty()) {
			Toast.makeText(context,
					getResources().getString(R.string.error_planname_null),
					Toast.LENGTH_SHORT).show();
			return false;
		}

		if (planDescription.getText().toString().isEmpty()) {
			planDescription.setText(getResources().getString(
					R.string.error_plandescription_null));
		}

		for (int i = 0; i < spotListView.getChildCount() - 1; i++) {
			SpotItem si = (SpotItem) spotListView.getChildAt(i);
			if (getString(R.string.default_edit_spot_name).equals(
					si.getSpotName().getText().toString())) {
				String text = String.format(
						getResources().getString(R.string.error_name_null), i);
				Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
				return false;
			}
			if (si.getChildCount() == 4) {
				String text = String.format(
						getResources().getString(R.string.error_consum_null),
						si.getSpotName().getText().toString());
				Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		return true;
	}

	private boolean cleanReleasedPlan(boolean all) {
		planName.setText("");
		planDescription.setText("");

		if (spotListView.getChildCount() > 2) {
			spotListView.removeViews(1, spotListView.getChildCount() - 2);
		}

		SpotItem cleanSpotItem = (SpotItem) spotListView.getChildAt(0);

		if (cleanSpotItem.getChildCount() > 4) {
			cleanSpotItem.removeViews(3, cleanSpotItem.getChildCount() - 4);
		}
		cleanSpotItem.getSpotName().setText(R.string.default_edit_spot_name);
		String defaultDate = tFormat.format(new Date());
		cleanSpotItem.getSpotDate().setText(
				defaultDate + UNDER_LINE + defaultDate);

		if (all) {
			spotListView.removeViewAt(0);
		}

		return true;

	}

	@Override
	public void onBackPressed() {
		if (compareBar.getVisibility() == View.VISIBLE) {
			hideInputBar(getWindow().getCurrentFocus());
			return;
		}
		if (mUser != null) {
			exitAlert();
		} else {
			finish();
		}
	}

	protected void loginAlert() {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle(R.string.login_title)
				.setMessage(R.string.login_hit)
				.setPositiveButton(R.string.login_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								login();
								return;
							}
						})
				.setNegativeButton(R.string.login_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								return;
							}
						}).create();
		alertDialog.show();
	}

	protected void exitAlert() {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle(R.string.exit_title)
				.setMessage(R.string.exit_hit)
				.setPositiveButton(R.string.exit_ok,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								finish();
							}
						})
				.setNegativeButton(R.string.exit_cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								updateTagUI(1);
								return;
							}
						}).create();
		alertDialog.show();
	}

	public void hideInputBar(View v) {
		compareBar.setVisibility(View.GONE);
		viewTab.setVisibility(View.VISIBLE);
		viewPaper.setScrollEnabled(true);

		if (v != null) {
			imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		}
	}

	protected void showUserInfo() {
		register.setVisibility(View.INVISIBLE);
		userTitleLayout.setVisibility(View.VISIBLE);
		if (mUser != null) {
			phoneNumber.setText(mUser.getUserName());
			if (mUser.getHeadRes() != 0) {
				head.setImageResource(mUser.getHeadRes());
			} else if (mUser.getHead() != null) {
				head.setImageBitmap(mUser.getHead());
			} else {
				int resId = getRandomPersonHeadRes();
				head.setImageResource(resId);
			}
		}
		head.setVisibility(View.VISIBLE);
		logoutBt.setVisibility(View.VISIBLE);
		viewPaper.setScrollEnabled(true);
	}

	public void login() {
		Intent intent = new Intent(this, LoginActivity.class);
		startActivityForResult(intent, LoginActivity.REQUEST_LOGIN);
		overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
	}

	public void logout(View v) {
		if (mUser != null) {
			mUser = null;
		}
		register.setVisibility(View.VISIBLE);
		userTitleLayout.setVisibility(View.INVISIBLE);
		logoutBt.setVisibility(View.GONE);
		viewPaper.setScrollEnabled(false);
		head.setVisibility(View.INVISIBLE);
		v.setVisibility(View.INVISIBLE);
		LoginInfo loginInfo = mSharePreferencesManager.readUserInfo();
		if (loginInfo.getAutoLogin()) {
			mSharePreferencesManager.writeUserInfo(false, loginInfo.getEmail(),
					loginInfo.getPassword());
		}
		Toast.makeText(context, "Logout", Toast.LENGTH_SHORT).show();
	}

	public void autoLogin() {
		LoginInfo loginInfo = mSharePreferencesManager.readUserInfo();
		if (loginInfo.getAutoLogin()) {
			if (loginInfo.getEmail().equals("test")
					&& loginInfo.getPassword().equals(
							"39FC42C96B8CE356EDF5A920835D0565")) {
				mUser = User.getDefaultUser();
				// showUserInfo();
				handler.sendEmptyMessage(2);
				return;
			}
			User user = new User(1, loginInfo.getEmail(), null, 1,
					loginInfo.getPassword());
			UserDataManager userDataManager = new UserDataManager(this);
			userDataManager.login(user, new UserDataLishenter() {
				@Override
				public void requestUserData(User user) {
					mUser = user;
					// showUserInfo();
					handler.sendEmptyMessage(2);
				}
			});
		}
	}

	protected void goUserHeadActivity() {
		Intent intent = new Intent(this, UserHeadActivity.class);
		intent.putExtra("fileTitle", mUser.getUserName());
		startActivity(intent);
		overridePendingTransition(R.anim.sub_enter, R.anim.main_exit);
	}

	public void setInputTarget(View inputTarget) {
		this.inputTarget = inputTarget;
		// spotScroll.smoothScrollTo(0, inputTarget.getTop());
	}

	public LinearLayout getCompareBar() {
		return compareBar;
	}

	@SuppressLint("Recycle")
	public List<Integer> getRandomPersonHeadRes(int count) {
		List<Integer> list = new ArrayList<Integer>();
		TypedArray headResTypedArray = getResources().obtainTypedArray(
				R.array.person_heads);
		for (int i = 0; i < count; i++) {
			int headRes = headResTypedArray.getResourceId(
					i % headResTypedArray.length(), 0);
			list.add(headRes);
		}
		Collections.shuffle(list);
		return list;
	}

	@SuppressLint("Recycle")
	public int getRandomPersonHeadRes() {
		TypedArray headRes = getResources().obtainTypedArray(
				R.array.person_heads);
		return headRes.getResourceId((int) (Math.random() * headRes.length()),
				0);
	}

	private void registerUserHeadReceiver() {
		IntentFilter intentFilter = new IntentFilter(UserHeadActivity.TAG);
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				Log.i("chengongguo", "registerUserHeadReceiver()");
				Bundle bundle = intent.getExtras();
				int headType = bundle.getInt("headType");
				if (headType == UserHeadActivity.HEAD_TYPE_RES) {
					int headRes = bundle.getInt("headRes");
					Log.i("chengongguo", "registerUserHeadReceiver() headRes="
							+ headRes);
					mUser.setHeadRes(headRes);
				} else if (headType == UserHeadActivity.HEAD_TYPE_FILE) {
					String fileName = bundle.getString("fileName");
					Log.i("chengongguo", "registerUserHeadReceiver() fileName="
							+ fileName);
					mUser.setHead(fileName);
				}
				// showUserInfo();
				handler.sendEmptyMessage(2);
			}
		}, intentFilter);
	}

	private List<Plan> diffPlans(List<Plan> nPlans, List<Plan> sPlans) {
		if (sPlans == null || sPlans.size() == 0) {
			return nPlans;
		}

		List<Plan> tempPlans = new ArrayList<Plan>();
		for (int i = 0; i < sPlans.size(); i++) {
			sPlans.get(i).setDelFlg(0);
			tempPlans.add(sPlans.get(i));
		}

		for (int i = 0; i < nPlans.size(); i++) {
			nPlans.get(i).setId(null);
			tempPlans.add(nPlans.get(i));
		}

		return tempPlans;
	}
}
